using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace AppEnvironment.Web
{
    //example:
    /*
       RepeaterBinder<DataTypeClass> bindAdaptor = new RepeaterBinder<DataTypeClass>();
       bindAdaptor.Bind(repeaterControl, datasourceArray,
          delegate
          {
             //.. bindAdaptor.Args.Item
             //.. bindAdaptor.Data
       });
    */

    /// <summary>
    /// Provides type-safe way to bind to a Repeater, using inline anonymous delegate
    /// </summary>
    /// <typeparam name="TBindType"></typeparam>
    internal class RepeaterBinder<TBindType> //this was made internal - use via Repeater.Assign
    {
        private RepeaterItemEventHandler mDestinationMethod;
        private RepeaterItemEventHandler DestinationMethod
        {
            get { return mDestinationMethod; }
            set { mDestinationMethod = value; }
        }

        private RepeaterItemEventArgs mArgs;
        public RepeaterItemEventArgs Args
        {
            get { return mArgs; }
            private set { mArgs = value; }
        }

        private RepeaterItem mItem;
        public RepeaterItem Item
        {
            get { return mItem; }
            private set { mItem = value; }
        }


        private TBindType mData;
        public TBindType Data
        {
            get { return mData; }
            private set { mData = value; }
        }

        private void AdaptEvent(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Args = e;
                Item = e.Item;
                Data = (TBindType)e.Item.DataItem;
                DestinationMethod(sender, Args);
            }
        }

        public void Bind(Repeater repeater, IEnumerable<TBindType> dataSource,
           RepeaterItemEventHandler onItemDataBound)
        {
            DestinationMethod = onItemDataBound;
            repeater.DataSource = dataSource;
            repeater.ItemDataBound += AdaptEvent;
            repeater.DataBind();
        }

        public void Bind(Repeater repeater, object dataSource,
           RepeaterItemEventHandler onItemDataBound)
        {
            DestinationMethod = onItemDataBound;
            repeater.DataSource = dataSource;
            repeater.ItemDataBound += AdaptEvent;
            repeater.DataBind();
        }

        public TControl Find<TControl>(string controlName)
           where TControl : Control
        {
            return Item.FindControl(controlName) as TControl;
        }
    }
}
